﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using MINERP.COM;
using MINERP.DAL;
using MINERP.MODEL.FoundationModel;

namespace MINERP.BLL.DisjoinProForOutShop
{
    public class ShippingBLL
    {
        public ShippingBLL()
        {

        }


        public delegate bool ASK_DEL();
        const string strMarkSelect = "√";
        public event ASK_DEL AskDel;
        /// <summary>
        /// 订单号获取快递信息
        /// </summary>
        /// <param name="inBagId"></param>
        /// <returns></returns>
        public ShippingView GetShippingInfo(int inBagId)
        {

            ShippingView shippingView = new ShippingView();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {

                CustomAddress customAddress = db.CustomAddress.FirstOrDefault(p => p.Tb_OrderBag.OrderBagId == inBagId);
                if (customAddress != null)
                {


                    customAddress.ShippingCompanyReference.Load();
                    customAddress.Tb_OrderBagReference.Load();
                    ShippingCompany shippingCompany = customAddress.ShippingCompany;

                    shippingView.CustomAddress = new CustomAddress_Info()
                    {
                        AddressID = customAddress.AddressID,
                        Area = customAddress.Area,
                        City = customAddress.City,
                        CityPart = customAddress.CityPart,
                        Company = customAddress.Company,
                        CountryCode = customAddress.CountryCode,
                        Firstname = customAddress.Firstname,
                        Lastname = customAddress.Lastname,
                        OrderBagId = customAddress.Tb_OrderBag.OrderBagId,
                        Phone = customAddress.Phone,
                        Province = customAddress.Province,
                        Salutation = customAddress.Salutation,
                        Street = customAddress.Street,
                        Zip = customAddress.Zip,
                        ShippingStatusContext = customAddress.ShippingStatusContext,
                        DeliveryReportStream = customAddress.DeliveryReportStream,
                        TotalPrice = customAddress.TotalPrice,
                        Mark = strMarkSelect,
                        MobilPhone = customAddress.MobilePhoneNum
                    };

                    shippingView.ShippingCompany = new ShippingCompany_Info() { ShippingCompanyName = shippingCompany.ShippingCompanyName, ShippingFormatPath = shippingCompany.ShippingFormatPath, TrackingUrl = shippingCompany.Tracking_url, Alias = shippingCompany.Alias };
                    CustomerPaymentInfo customerPaymentInfo =
                           db.CustomerPaymentInfo.FirstOrDefault(p => p.paymentID == customAddress.paymentID);
                    if (customerPaymentInfo != null)
                    {
                        shippingView.CustomerPayment = new CustomerPaymentInfo_Info()
                        {
                            PaymentCode = customerPaymentInfo.paymentID,
                            PaymentID = customerPaymentInfo.paymentID,
                            PaymentName = customerPaymentInfo.paymentName
                        };
                    }
                    else
                    {
                        shippingView.CustomerPayment = new CustomerPaymentInfo_Info();
                    }
                }
                else
                {
                    CustomAddress_bk customAddressbk =
                        db.CustomAddress_bk.FirstOrDefault(p => p.Tb_OrderBag_BK.OrderBagId == inBagId);
                    customAddressbk.ShippingCompanyReference.Load();
                    customAddressbk.Tb_OrderBag_BKReference.Load();
                    ShippingCompany shippingCompany = customAddressbk.ShippingCompany;

                    shippingView.CustomAddress = new CustomAddress_Info()
                    {
                        AddressID = customAddressbk.AddressID,
                        Area = customAddressbk.Area,
                        City = customAddressbk.City,
                        CityPart = customAddressbk.CityPart,
                        Company = customAddressbk.Company,
                        CountryCode = customAddressbk.CountryCode,
                        Firstname = customAddressbk.Firstname,
                        Lastname = customAddressbk.Lastname,
                        OrderBagId = customAddressbk.Tb_OrderBag_BK.OrderBagId,
                        Phone = customAddressbk.Phone,
                        Province = customAddressbk.Province,
                        Salutation = customAddressbk.Salutation,
                        Street = customAddressbk.Street,
                        Zip = customAddressbk.Zip,
                        ShippingStatusContext = customAddressbk.ShippingStatusContext,
                        DeliveryReportStream = customAddressbk.DeliveryReportStream,
                        TotalPrice = customAddressbk.TotalPrice,
                        Mark = strMarkSelect,
                        MobilPhone = customAddressbk.MobilePhone
                    };
                    shippingView.ShippingCompany = new ShippingCompany_Info() { ShippingCompanyName = shippingCompany.ShippingCompanyName, ShippingFormatPath = shippingCompany.ShippingFormatPath, TrackingUrl = shippingCompany.Tracking_url, Alias = shippingCompany.Alias };
                    CustomerPaymentInfo customerPaymentInfo =
                               db.CustomerPaymentInfo.FirstOrDefault(p => p.paymentID == customAddressbk.paymentID);
                    if (customerPaymentInfo != null)
                    {
                        shippingView.CustomerPayment = new CustomerPaymentInfo_Info()
                        {
                            PaymentCode = customerPaymentInfo.paymentCode,
                            PaymentID = customerPaymentInfo.paymentID,
                            PaymentName = customerPaymentInfo.paymentName
                        };
                    }
                    else
                    {
                        shippingView.CustomerPayment = new CustomerPaymentInfo_Info();
                    }
                }

            }
            return shippingView;
        }
        /// <summary>
        /// 产品号获取快递信息
        /// </summary>
        /// <param name="inOrderProductid"></param>
        /// <returns></returns>
        public ShippingView GetShippingInfoByProductid(int inOrderProductid)
        {
            ShippingView shippingView = new ShippingView();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {

                CustomAddress customAddress = db.CustomAddress.FirstOrDefault(p => p.Tb_OrderBag.orderInfo.FirstOrDefault(pi => pi.OrderProductId == inOrderProductid) != null);
                if (customAddress != null)
                {
                    customAddress.ShippingCompanyReference.Load();
                    customAddress.Tb_OrderBagReference.Load();
                    ShippingCompany shippingCompany = customAddress.ShippingCompany;
                    if (shippingCompany != null)
                    {
                        shippingView.CustomAddress = new CustomAddress_Info()
                        {
                            AddressID = customAddress.AddressID,
                            Area = customAddress.Area,
                            City = customAddress.City,
                            CityPart = customAddress.CityPart,
                            Company = customAddress.Company,
                            CountryCode = customAddress.CountryCode,
                            Firstname = customAddress.Firstname,
                            Lastname = customAddress.Lastname,
                            OrderBagId = customAddress.Tb_OrderBag.OrderBagId,
                            Phone = customAddress.Phone,
                            Province = customAddress.Province,
                            Salutation = customAddress.Salutation,
                            Street = customAddress.Street,
                            Zip = customAddress.Zip,
                            ShippingStatusContext = customAddress.ShippingStatusContext,
                            DeliveryReportStream = customAddress.DeliveryReportStream,
                            Mark = strMarkSelect,
                            TotalPrice = customAddress.TotalPrice,
                            MobilPhone = customAddress.MobilePhoneNum

                        };
                        shippingView.ShippingCompany = new ShippingCompany_Info()
                        {
                            ShippingCompanyName = shippingCompany.ShippingCompanyName,
                            ShippingFormatPath = shippingCompany.ShippingFormatPath,
                            TrackingUrl = shippingCompany.Tracking_url,
                            Alias = shippingCompany.Alias
                        };
                        CustomerPaymentInfo customerPaymentInfo =
                            db.CustomerPaymentInfo.FirstOrDefault(p => p.paymentID == customAddress.paymentID);
                        if (customerPaymentInfo != null)
                        {
                            shippingView.CustomerPayment = new CustomerPaymentInfo_Info()
                            {
                                PaymentCode = customerPaymentInfo.paymentID,
                                PaymentID = customerPaymentInfo.paymentID,
                                PaymentName = customerPaymentInfo.paymentName
                            };
                        }
                        else
                        {
                            shippingView.CustomerPayment = new CustomerPaymentInfo_Info();
                        }
                    }
                    else
                    {
                        shippingView.CustomAddress = new CustomAddress_Info();
                        shippingView.ShippingCompany = new ShippingCompany_Info();
                        shippingView.CustomerPayment = new CustomerPaymentInfo_Info();
                    }

                }
                else
                {
                    CustomAddress_bk customAddressbk =
                        db.CustomAddress_bk.FirstOrDefault(p => p.Tb_OrderBag_BK.orderInfo_BK.FirstOrDefault(pi => pi.OrderProductId == inOrderProductid) != null);
                    if (customAddressbk != null)
                    {
                        customAddressbk.ShippingCompanyReference.Load();
                        customAddressbk.Tb_OrderBag_BKReference.Load();
                        ShippingCompany shippingCompany = customAddressbk.ShippingCompany;
                        if (shippingCompany != null)
                        {
                            shippingView.CustomAddress = new CustomAddress_Info()
                            {
                                AddressID = customAddressbk.AddressID,
                                Area = customAddressbk.Area,
                                City = customAddressbk.City,
                                CityPart = customAddressbk.CityPart,
                                Company = customAddressbk.Company,
                                CountryCode = customAddressbk.CountryCode,
                                Firstname = customAddressbk.Firstname,
                                Lastname = customAddressbk.Lastname,
                                OrderBagId = customAddressbk.Tb_OrderBag_BK.OrderBagId,
                                Phone = customAddressbk.Phone,
                                Province = customAddressbk.Province,
                                Salutation = customAddressbk.Salutation,
                                Street = customAddressbk.Street,
                                Zip = customAddressbk.Zip,
                                ShippingStatusContext =
                                    customAddressbk.ShippingStatusContext,
                                PaymentID = customAddressbk.paymentID,
                                DeliveryReportStream = customAddressbk.DeliveryReportStream,
                                Mark = strMarkSelect,
                                TotalPrice = customAddressbk.TotalPrice,
                                MobilPhone = customAddressbk.MobilePhone
                            };
                            shippingView.ShippingCompany = new ShippingCompany_Info()
                            {
                                ShippingCompanyName =
                                    shippingCompany.ShippingCompanyName,
                                ShippingFormatPath =
                                    shippingCompany.ShippingFormatPath,
                                TrackingUrl = shippingCompany.Tracking_url,
                                Alias = shippingCompany.Alias
                            };
                            CustomerPaymentInfo customerPaymentInfo =
                                db.CustomerPaymentInfo.FirstOrDefault(p => p.paymentID == customAddressbk.paymentID);
                            if (customerPaymentInfo != null)
                            {
                                shippingView.CustomerPayment = new CustomerPaymentInfo_Info()
                                {
                                    PaymentCode = customerPaymentInfo.paymentCode,
                                    PaymentID = customerPaymentInfo.paymentID,
                                    PaymentName = customerPaymentInfo.paymentName
                                };
                            }
                            else
                            {
                                shippingView.CustomerPayment = new CustomerPaymentInfo_Info();
                            }
                        }
                        else
                        {
                            shippingView.CustomAddress = new CustomAddress_Info();
                            shippingView.ShippingCompany = new ShippingCompany_Info();
                            shippingView.CustomerPayment = new CustomerPaymentInfo_Info();
                        }
                    }
                    else
                    {
                        shippingView.CustomAddress = new CustomAddress_Info();
                        shippingView.ShippingCompany = new ShippingCompany_Info();
                        shippingView.CustomerPayment = new CustomerPaymentInfo_Info();
                    }
                }

            }
            return shippingView;
        }

        public void ReflectToIPG(ShippingView inShippingView, string shippingTickekNo)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                CustomAddress customAddress =
                    db.CustomAddress.FirstOrDefault(P => P.AddressID == inShippingView.CustomAddress.AddressID);
                if (customAddress != null)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    customAddress.Tb_OrderBagReference.Load();
                    if (customAddress.Tb_OrderBag.Type == (int)OrderBagType.RemoteOrder)
                    {
                        //写入shiffd
                        stringBuilder.AppendLine("tracking_id=" + shippingTickekNo);
                        //stringBuilder.AppendLine("tracking_url=http://" + inShippingView.ShippingCompany.TrackingUrl + "");
                        //stringBuilder.AppendLine(string.Format(inShippingView.ShippingCompany.TrackingUrl, shippingTickekNo));
                        stringBuilder.AppendLine(inShippingView.ShippingCompany.TrackingUrl);
                        stringBuilder.AppendLine("shipping_privider=" + inShippingView.ShippingCompany.ShippingCompanyName);
                        FileDirPath fileDirPath = db.FileDirPath.FirstOrDefault(p => p.id == 8);
                        if (fileDirPath != null)
                        {
                            String feedPath = fileDirPath.FileDir;
                            string DirPath = feedPath + "\\" + customAddress.Tb_OrderBag.BagName.Split('_')[0];
                            if (!Directory.Exists(DirPath))
                            {
                                Directory.CreateDirectory(DirPath);
                            }
                            string fileFullPath = feedPath + "\\" + customAddress.Tb_OrderBag.BagName.Split('_')[0] + "\\status.SHIPPED";
                            StreamWriter sw = null;
                            try
                            {
                                if (File.Exists(fileFullPath))
                                {
                                    if (AskDel())
                                    {
                                        File.Delete(fileFullPath);
                                        // File.Create(fileFullPath);
                                        sw = File.CreateText(fileFullPath);
                                        sw.Write(stringBuilder);

                                    }
                                }
                                else
                                {
                                    sw = File.CreateText(fileFullPath);
                                    sw.Write(stringBuilder);
                                }//将数据保存Tb_FujOrderInfo
                                if (!string.IsNullOrEmpty(shippingTickekNo))
                                {
                                    try
                                    {
                                        string strRemoteID = customAddress.Tb_OrderBag.BagName.Substring(0, customAddress.Tb_OrderBag.BagName.IndexOf('_'));
                                        List<MINERP.DAL.Tb_FujOrderInfo> listInfo = db.Tb_FujOrderInfo.Where(p => p.OrderNum == strRemoteID).ToList();
                                        foreach (MINERP.DAL.Tb_FujOrderInfo info in listInfo)
                                        {
                                            info.ShippingNO = shippingTickekNo;
                                        }
                                    }
                                    catch
                                    {


                                    }

                                }

                                //listInfo.ForEach(p => p.ShippingNO = strRemoteID);
                                db.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                WriteLogForCheck.WriteLogFile(DateTime.Now + ex.ToString());
                                throw;
                            }
                            finally
                            {
                                if (sw != null)
                                {
                                    sw.Close();
                                }

                            }

                            //修改order.xml
                            string fileOrderXmlPath = feedPath + "\\" + customAddress.Tb_OrderBag.BagName.Split('_')[0] + "\\order.xml.prod";
                            string fileOrderXmlMew = feedPath + "\\" + customAddress.Tb_OrderBag.BagName.Split('_')[0] + "\\order.xml";
                            if (File.Exists(fileOrderXmlPath))
                            {
                                WriteLogForCheck.WriteLogFile(DateTime.Now + "准备移动从" + fileOrderXmlPath + "移动到:" + fileOrderXmlMew);

                                if (File.Exists(fileOrderXmlMew))
                                    File.Delete(fileOrderXmlMew);

                                File.Move(fileOrderXmlPath, fileOrderXmlMew);
                                WriteLogForCheck.WriteLogFile(DateTime.Now + "移动完成!");

                            }
                            else
                            {
                                WriteLogForCheck.WriteLogFile(DateTime.Now + "：" + customAddress.Tb_OrderBag.BagName.Split('_')[0] + "的order.xml.prod文件不存在");
                            }
                        }


                    }

                }
                else//备份表里找
                {
                    CustomAddress_bk customAddressbk =
                        db.CustomAddress_bk.FirstOrDefault(P => P.AddressID == inShippingView.CustomAddress.AddressID);
                    if (customAddressbk != null)
                    {


                        StringBuilder stringBuilder = new StringBuilder();
                        customAddressbk.Tb_OrderBag_BKReference.Load();
                        if (customAddressbk.Tb_OrderBag_BK.Type == (int)OrderBagType.RemoteOrder)
                        {
                            stringBuilder.AppendLine("tracking-id=" + shippingTickekNo);
                            //stringBuilder.AppendLine("tracking_url=http://" + inShippingView.ShippingCompany.TrackingUrl +
                            //                        "");
                            //stringBuilder.AppendLine(string.Format(inShippingView.ShippingCompany.TrackingUrl, shippingTickekNo));
                            stringBuilder.AppendLine(inShippingView.ShippingCompany.TrackingUrl);
                            stringBuilder.AppendLine("shipping_privider=" +
                                                     inShippingView.ShippingCompany.ShippingCompanyName);
                            FileDirPath fileDirPath = db.FileDirPath.FirstOrDefault(p => p.id == 8);
                            if (fileDirPath != null)
                            {
                                String feedPath = fileDirPath.FileDir;
                                string fileFullPath = feedPath + "\\" +
                                                      customAddressbk.Tb_OrderBag_BK.BagName.Split('_')[0] +
                                                      "\\status.SHIPPED";
                                StreamWriter sw = null;
                                try
                                {
                                    if (File.Exists(fileFullPath))
                                    {
                                        if (AskDel())
                                        {
                                            File.Delete(fileFullPath);
                                            // File.Create(fileFullPath);
                                            sw = File.CreateText(fileFullPath);
                                            sw.Write(stringBuilder);

                                            ;
                                        }
                                    }
                                    else
                                    {
                                        sw = File.CreateText(fileFullPath);
                                        sw.Write(stringBuilder);
                                    }
                                    //将数据保存Tb_FujOrderInfo
                                    if (!string.IsNullOrEmpty(shippingTickekNo))
                                    {
                                        try
                                        {

                                            string strRemoteID = customAddressbk.Tb_OrderBag_BK.BagName.Substring(0, customAddressbk.Tb_OrderBag_BK.BagName.IndexOf('_'));
                                            List<MINERP.DAL.Tb_FujOrderInfo> listInfo = db.Tb_FujOrderInfo.Where(p => p.OrderNum == strRemoteID).ToList();
                                            foreach (MINERP.DAL.Tb_FujOrderInfo info in listInfo)
                                            {
                                                info.ShippingNO = shippingTickekNo;
                                            }
                                        }
                                        catch
                                        {

                                        }
                                    }
                                    //listInfo.ForEach(p => p.ShippingNO = strRemoteID);
                                    db.SaveChanges();
                                }
                                catch (Exception exception)
                                {
                                    WriteLogForCheck.WriteLogFile(DateTime.Now + exception.ToString());
                                }
                                finally
                                {
                                    sw.Close();
                                }

                                //修改order.xml
                                string fileOrderXmlPath = feedPath + "\\" + customAddressbk.Tb_OrderBag_BK.BagName.Split('_')[0] + "\\order.xml.prod";
                                string fileOrderXmlMew = feedPath + "\\" + customAddressbk.Tb_OrderBag_BK.BagName.Split('_')[0] + "\\order.xml";
                                if (File.Exists(fileOrderXmlPath))
                                {
                                    WriteLogForCheck.WriteLogFile(DateTime.Now + "准备移动从" + fileOrderXmlPath + "移动到:" + fileOrderXmlMew);

                                    if (File.Exists(fileOrderXmlMew))
                                        File.Delete(fileOrderXmlMew);

                                    File.Move(fileOrderXmlPath, fileOrderXmlMew);
                                    WriteLogForCheck.WriteLogFile(DateTime.Now + "移动完成!");

                                }
                                else
                                {
                                    WriteLogForCheck.WriteLogFile(DateTime.Now + "：" + customAddressbk.Tb_OrderBag_BK.BagName.Split('_')[0] + "的order.xml.prod文件不存在");
                                }
                            }
                        }

                    }

                }


            }

        }
    }
    public class ShippingView
    {
        public CustomAddress_Info CustomAddress { set; get; }
        public ShippingCompany_Info ShippingCompany { set; get; }
        public CustomerPaymentInfo_Info CustomerPayment { get; set; }

    }
}
